<?php

declare(strict_types=1);

namespace App\Http\Controllers\Manage;

use App\Models\Supplier;
use App\Repositories\Manage\MenuRepository;
use App\Repositories\Manage\RoleRepository;
use App\Repositories\Manage\UserRepository;
use Think\Exception;

class UserController extends ManageBaseController
{
    private $userRep = NULL;

    public function __construct(
        UserRepository $userRep
    )
    {
        parent::__construct();
        $this->userRep = $userRep;
    }

    public function index()
    {
        $filter = request()->all();
        $res = $this->userRep->getList($filter, $this->pageNum, $this->pageSize);

        /*  $password = "123456";
          foreach ($res['items'] as $k => $v) {
              $salt = gen_salt(8);
              $pass = genPassword($password . $salt);
              User::where("id", $v['id'])->update([
                  'salt' => $salt,
                  'password' => $pass
              ]);
          }
          */

        return retSuc($res);
    }

    public function update($id = null)
    {
        $data = request()->all();

        try {

            $last_id = $this->userRep->saveOrUpdate([
                'gender' => $data['gender'],
                'nickname' => $data['nickname'],
                'username' => $data['username'],
                'mobile' => $data['mobile'],
                'email' => $data['email'],
                'shop_id' => $data['shop_id'] ?? NULL,
                'status' => $data['status'] ?? 1,
            ], $id ?? 0);

            if (!$last_id) {
                return retFail("更新失败");
            }

            if ($last_id && !empty($data['roleIds'])) {//更新权限
                $this->userRep->saveRoles($last_id, $data['roleIds']);
            }

            $res = $this->userRep->getOne($last_id);
            return retSuc($res);
        } catch (Exception $e) {
            return retFail($e->getMessage());
        }
    }

    public function detail($id = 0)
    {
        $id = intval($id);
        if (!$id)
            return retFail("参数错误");

        $res = $this->userRep->getOne($id);

        return retSuc($res);
    }

    public function me()
    {
        /*return retSuc([
            'username' => "admin",
            'nickname' => "系统管理员",
            'avatar' => "https://oss.youlai.tech/youlai-boot/2023/05/16/811270ef31f548af9cffc026dfc3777b.gif",
            'userId' => 2,
            'perms' => (new MenuRepository())->getPermByUserId(1),
            'roles' => $this->userRep->getRoleCodeByUsesrId(1),
        ]);*/
        $res = $this->userRep->getOne(UID);
        $shopreset_pass = Supplier::query()->where(['id' => $res['shop_id']])->first(['id', 'type']);
        return retSuc([
            'username' => $res['username'],
            'nickname' => $res['username'],
            'avatar' => $res['avatar'] ?? "",
            'userId' => $res['id'],
            'shop_type' => $shop['type'] ?? 0,
            'perms' => (new MenuRepository())->getPermByUserId($res['id']),
            'roles' => $this->userRep->getRoleCodeByUsesrId($res['id']),
        ]);

    }

    public function delete($id)
    {
        $id = intval($id);
        if (empty($id)) {
            return retFail("参数错误");
        }

        $role_users = (new RoleRepository())->getRoleUser("SUPER");
        $userIds = get_column($role_users, 'id');
        if (count($userIds) == 1 && in_array($id, $userIds)) {
            return retFail("至少要保留一个超级管理员");
        }

        return $this->userRep->batchDelete($id);
    }

    /**
     * 更改密码
     * @param null $id
     */
    public function reset_pass($id = null)
    {
        $id = intval($id);
        if (!$id)
            return retFail("参数错误");

        $res = $this->userRep->getOne($id);
        if (empty($res)) {
            return retFail("会员不存在");
        }

        if (!checkIsSuper(UID)) {
            $shop_id = getUserRelateShopId(UID);

            if ($shop_id == $res['shop_id'])
                return retFail("无修改权限");
        }

        $password = trim(request()->get("password"));
        if (empty($password)) {
            return retFail("密码必填");
        }

        if (strlen($password) < 6) {
            return retFail("密码至少6位");
        }

        $this->userRep->resetPassword(intval($id), $password);
        return retSuc([], "重置成功");
    }


}
